package com.batunite.livedatabinding.views

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.SurfaceHolder
import android.view.SurfaceView
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

/**
 * 测试gpt写的tetris
 */
class TetrisView(context: Context, attrs: AttributeSet?) : SurfaceView(context, attrs),
    SurfaceHolder.Callback {

    private var gameThread: GameThread? = null
    private var tetrisGame: TetrisGame? = null

    init {
        holder.addCallback(this)
    }

    fun startGame() {
        tetrisGame = TetrisGame()
        gameThread = GameThread(holder, tetrisGame!!)
        gameThread?.start()
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        // 启动游戏
        startGame()
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
        // 不需要在此做处理
    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {
        // 结束游戏
        gameThread?.stopGame()
        gameThread = null
        tetrisGame = null
    }
}

class TetrisGame {
    private val boardWidth = 10
    private val boardHeight = 20
    private val blockSize = 50
    private var board: Array<BooleanArray> = Array(boardHeight) { BooleanArray(boardWidth) }

    private val shapes = arrayOf(
        intArrayOf(1, 3, 5, 7), // I-shape
        intArrayOf(2, 4, 5, 7), // Z-shape
        intArrayOf(3, 5, 4, 6), // S-shape
        intArrayOf(3, 5, 4, 7), // T-shape
        intArrayOf(2, 3, 5, 7), // L-shape
        intArrayOf(3, 5, 7, 6), // J-shape
        intArrayOf(2, 3, 4, 5)  // O-shape
    )

    private var currentShape: IntArray = IntArray(4)
    private var currentX = 0
    private var currentY = 0

    private val paint: Paint = Paint().apply {
        color = Color.RED
        style = Paint.Style.FILL
    }

    fun update() {
        // 更新游戏逻辑
        moveDown()
    }

    fun draw(canvas: Canvas) {
        // 绘制游戏画面
        canvas.drawColor(Color.WHITE)
        drawBoard(canvas)
        drawCurrentShape(canvas)
    }

    private fun drawBoard(canvas: Canvas) {
        for (row in board.indices) {
            for (col in board[row].indices) {
                if (board[row][col]) {
                    val left = col * blockSize.toFloat()
                    val top = row * blockSize.toFloat()
                    val right = left + blockSize
                    val bottom = top + blockSize
                    canvas.drawRect(left, top, right, bottom, paint)
                }
            }
        }
    }

    private fun drawCurrentShape(canvas: Canvas) {
        for (i in 0 until 4) {
            val row = currentY + currentShape[i] / 4
            val col = currentX + currentShape[i] % 4
            val left = col * blockSize.toFloat()
            val top = row * blockSize.toFloat()
            val right = left + blockSize
            val bottom = top + blockSize
            canvas.drawRect(left, top, right, bottom, paint)
        }
    }

    private fun moveDown() {
        // 检查是否可以下移
        if (canMove(0, 1)) {
            currentY++
        } else {
            // 将当前方块固定到游戏区域
            fixToBoard()
            checkLines()
            generateShape()
        }
    }

    private fun canMove(dx: Int, dy: Int): Boolean {
        for (i in 0 until 4) {
            val newRow = currentY + currentShape[i] / 4 + dy
            val newCol = currentX + currentShape[i] % 4 + dx

            // 检查是否越界或与已有方块重叠
            if (newRow >= boardHeight || newCol < 0 || newCol >= boardWidth || (newRow >= 0 && board[newRow][newCol])) {
                return false
            }
        }
        return true
    }

    private fun fixToBoard() {
        for (i in 0 until 4) {
            val row = currentY + currentShape[i] / 4
            val col = currentX + currentShape[i] % 4
            board[row][col] = true
        }
    }

    private fun checkLines() {
        var fullLines = mutableListOf<Boolean>()
        for (row in 0 until boardHeight) {
            var isRowFull = true
            for (col in 0 until boardWidth) {
                if (!board[row][col]) {
                    isRowFull = false
                    break
                }
            }
            fullLines.add(isRowFull)
        }

        for (i in fullLines.indices) {
            if (fullLines[i]) {
                // 移除满行
                for (row in i downTo 1) {
                    System.arraycopy(board[row - 1], 0, board[row], 0, boardWidth)
                }
                // 顶部添加新行
                board[0] = BooleanArray(boardWidth)
            }
        }
    }

    private fun generateShape() {
        val random = shapes.random()
        System.arraycopy(random, 0, currentShape, 0, 4)
        currentX = boardWidth / 2 - 2
        currentY = 0
    }
}

class GameThread(private val surfaceHolder: SurfaceHolder, private val tetrisGame: TetrisGame) :
    Thread() {
    private var running = false

    fun stopGame() {
        running = false
        join()
    }

    override fun run() {
        running = true
        while (running) {
            val canvas: Canvas? = surfaceHolder.lockCanvas()
            if (canvas != null) {
                synchronized(surfaceHolder) {
                    tetrisGame.update()
                    tetrisGame.draw(canvas)
                }
                surfaceHolder.unlockCanvasAndPost(canvas)
            }
            sleep(16) // 控制刷新率（60帧每秒）
        }
    }
}
